<template>
  <div class="container"
       id="mapContainer">
    <div class="search-bar">
      <input class="search-input"
             placeholder="请输入关键字"
             v-model="searchName" />
      <a class="search-a"
         @click="searchMap">搜索</a>
    </div>
    <div class="map-show">
      <div class="map-content"
           id="mapContent"
           :style="{height:height}">

      </div>
      <div class="select-result">
        地址：<label>{{resultAddress}}</label>
        <button class="button-small"
                style="float: right;margin: 7px 10px;"
                @click="confirmAddress">确定</button>
      </div>
    </div>

    <div class="map-result"
         id="resultList">

    </div>
  </div>
</template>

<script>
import wx from "weixin-js-sdk";
export default {
  name: "bai-du-map-content",
  mounted() {
    this.wxConfig();
    this.initWeixin();
    this.initMap();
    this.goToLocation();
  },
  data() {
    return {
      searchName: "",
      resultAddress: "",
      map: "",
      point: {},
      maker: {},
      searchShow: false,
      height: "300px",
      provinceName: "",
      cityName: ""
    };
  },
  methods: {
    initMap() {
      var _self = this;
      // 创建地图实例
      if (!_self.point) {
        _self.point = new BMap.Point(116.404, 39.915);
      }
      _self.map = new BMap.Map("mapContent");
      _self.map.centerAndZoom(_self.point, 11);
      _self.map.addControl(new BMap.MapTypeControl());
      _self.map.enableScrollWheelZoom(true);
      _self.map.enableDoubleClickZoom(true);
      _self.maker = new BMap.Marker(_self.point);
      _self.map.addOverlay(_self.maker);
      _self.map.enableScrollWheelZoom(true);
      _self.map.addEventListener("click", _self.mapClick);

      _self.height = document.documentElement.clientHeight - 110 + "px";
    },
    searchMap() {
      var _self = this;
      _self.map = new BMap.Map("mapContent"); // 创建Map实例

      var local = new BMap.LocalSearch(_self.map, {
        renderOptions: { map: _self.map, panel: "resultList" },
        localResult: {},
        onSearchComplete: function(results) {
          //点击搜索面板事件
          $(document).on("click", "#resultList li", function() {
            console.log(this);
            var spans = this.getElementsByTagName("span");
            _self.resultAddress = spans[spans.length - 1].innerHTML;
          });
          _self.provinceName = results.province;
          _self.cityName = results.city;
        }
      });
      _self.map.addEventListener("click", _self.mapClick);
      local.search(this.searchName);
      _self.height = "300px";
    },
    //地图单击事件
    mapClick(e) {
      var _self = this;
      //单击之后添加标注，修改当前选择的地址
      _self.map.clearOverlays();
      _self.point = new BMap.Point(e.point.lng, e.point.lat);
      _self.marker = new BMap.Marker(_self.point); // 创建标注
      _self.map.addOverlay(_self.marker);
      //根据坐标解析详细地址
      _self.getAddress(e.point);
    },
    //定位当前位置
    setLocation() {
      //调用微信内置定位获取坐标
      var _self = this;
      //优先调用H5定位，否则调用ip定位
      var geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function(r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          _self.point = r.point;
          _self.maker = new BMap.Marker(r.point);
          _self.map.addOverlay(_self.maker);
          _self.map.panTo(r.point);
          _self.getAddress(r.point);
        } else {
          //ip定位 返回城市级别的定位
          function myFun(result) {
            var cityName = result.name;
            _self.map.centerAndZoom(cityName);
            _self.resultAddress = cityName;
          }
          var myCity = new BMap.LocalCity();
          if (myCity) {
            myCity.get(myFun);
          } else {
            _self.initMap();
          }
        }
      });
    },
    //解析地址
    getAddress(point) {
      var _self = this;
      var geoc = new BMap.Geocoder();
      geoc.getLocation(point, function(rs) {
        var addComp = rs.addressComponents;
        _self.provinceName = addComp.province;
        _self.cityName = addComp.city;
        // _self.resultAddress = addComp.province + addComp.city +  addComp.district + addComp.street  + addComp.streetNumber
        _self.resultAddress =
          addComp.district + addComp.street + addComp.streetNumber;
      });
    },
    //确定地址
    confirmAddress() {
      var _self = this;
      var address = {
        provinceName: _self.provinceName,
        cityName: _self.cityName,
        resultAddress: _self.resultAddress
      };
      _self.$emit("address", address);
    },

    //////////////////////////////////微信地理位置////////////////////////////////////
    wxConfig() {
      //微信配置
      var currUrl = location.href.split("#")[0];
      var body = {};
      body.params = {
        url: currUrl
      };
      var url = this.utilHelper.apiUrl + "/api/js_ticket";
      this.$http.post(url, body).then(
        response => {
          var data = response.body.resData;
          wx.config({
            debug: false,
            appId: data.appid, // 必填，公众号的唯一标识
            timestamp: data.time, // 必填，生成签名的时间戳
            nonceStr: data.noncestr, // 必填，生成签名的随机串
            signature: data.signature, // 必填，签名，见附录1
            jsApiList: ["getLocation"]
          });
        },
        res => {
          this.setLocation();
        }
      );
    },
    initWeixin() {
      var _self = this;
      var weixinHander = true;
      wx.ready(function() {
        _self.goToLocation();
        weixinHander = false;
      });
      wx.error(function() {
        _self.setLocation();
        weixinHander = false;
      });
      if (weixinHander) {
        _self.setLocation();
      }
    },
    goToLocation() {
      var _self = this;
      wx.getLocation({
        success: function(res) {
          var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
          //lat = res.latitude;

          var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
          var x = res.longitude;
          var y = res.latitude;
          console.log("location is lng=" + x + "  lat=" + y);
          //changCoordinate(x, y);
          //alert("location1 is lng=" + lng + "  lat=" + lat);
          var url =
            "http://api.map.baidu.com/geoconv/v1/?coords=" +
            x +
            "," +
            y +
            "&from=1&to=5&ak=j2bGq5pgdwBDdhBPL9iGZO5Gcy8OHehh";
          $.get(
            url,
            function(data) {
              if (data.status === 0) {
                var lng = data.result[0].x;
                var lat = data.result[0].y;
                //转换后的地址 定位到地图上
                _self.point = new BMap.Point(lng, lat);
                _self.initMap();
                _self.getAddress(_self.point);
              }
            },
            "jsonp"
          );

          var speed = res.speed; // 速度，以米/每秒计
          var accuracy = res.accuracy; // 位置精度
        },
        cancel: function(res) {
          _self.setLocation();
        },
        fail: function(res) {}
      });
    }
  }
};
</script>

<style scoped>
.search-bar {
  text-align: center;
  margin: 10px 0;
}
.search-input {
  width: 80%;
  border-radius: 5px;
  height: 35px;
}
.search-a {
  color: #d58512;
}
.map-content {
  width: 100%;
}
.map-show {
  width: 100%;
}
.select-result {
  margin: 10px 0;
  height: 35px;
  line-height: 35px;
}
</style>